﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Security.Claims;
using DB.Core.Models;
using Furion;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PMBF.Core.Enums;
using PMBF.Core.Handler;
using PMBF.Core.ViewModels;
using SqlSugar;

namespace PMBF.Application.Api
{
    [AppAuthorize, ApiDescriptionSettings("菜单管理")]
    [UserApiAuthenticationActionFilter]
    public class MenuRuleService : IDynamicApiController
    {
        private readonly ISqlSugarRepository repository;
        private readonly SqlSugarClient db;
        private readonly int ModelId = 37;

        public MenuRuleService(ISqlSugarRepository sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            db = repository.Context;
        }

        #region 查询列表、编辑、保存、禁用、删除

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="_query"></param>
        /// <returns></returns>
        public Model Post(ApiModelsQuerys _query)
        {
            _query.istree = true;
            _query.treeid = "id";
            _query.treeparentid = "parentMenuRuleID";

            return new ModelsService(repository).Model(ModelId, _query);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="_query"></param>
        /// <returns></returns>
        [NonUnify]
        public IActionResult PostExport(ApiModelsQuerys _query)
        {
            return new ModelsService(repository).Export(ModelId, _query);
        }

        /// <summary>
        /// 新增编辑，获取信息
        /// </summary>
        /// <param name="_id"></param>
        /// <returns></returns>
        public dynamic GetInfo(int _id)
        {
            var page = new ModelsService(repository).GetEditData(ModelId);

            if (_id != 0)
            {
                page.Page.Title = "编辑菜单";
                page.DataSource = db.Queryable<MenuRule>().Where(n => n.ID == _id).First();
            }
            else
            {
                page.Page.Title = "新增菜单";
                //page.DataSource = db.Queryable<MenuRule>().Where(n => n.ID == _id).First();
            }

            return page;
        }

        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public dynamic PostSave(MenuRule model)
        {
            bool isok = false;

            if (model.ID == 0)
            {
                model.ModifyTime = DateTime.Now;
                model.ModifyUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                model.CreateTime = DateTime.Now;
                model.CreateUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                model.DeleteFlag = 0;
                isok = db.Insertable(model).ExecuteCommand() > 0;
            }
            else
            {
                model.ModifyTime = DateTime.Now;
                model.ModifyUserID = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
                isok = db.Updateable(model).IgnoreColumns(ignoreAllNullColumns: true).IgnoreColumns("CreateTime", "CreateUserID").ExecuteCommand() > 0;
            }

            if (isok == false)
            {
                throw Oops.Oh(SystemErrorCodes.E0010);
            }

            return new { Success = true, message = "保存成功" };
        }


        /// <summary>
        /// 正常数据，将数据删除标志设置成已删除
        /// </summary>
        /// <returns></returns>
        public dynamic PostDisable(ApiPostExtendModel data)
        {
            int userId = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
            foreach (int id in data.ids)
            {
                db.Updateable<MenuRule>().SetColumns(n => new MenuRule()
                {
                    DeleteFlag = 1,
                    DeleteTime = DateTime.Now,
                    DeleteUserID = userId

                }).Where(n => n.ID == id).ExecuteCommand();
            }

            return new { Success = true, message = "删除成功" };
        }


        /// <summary>
        /// 有数据删除标志设置的直接删除
        /// </summary>
        /// <returns></returns>
        public dynamic PostDelete(ApiPostExtendModel data)
        {
            foreach (int id in data.ids)
            {
                db.Deleteable<MenuRule>().Where(n => n.ID == id && n.DeleteFlag == 1).ExecuteCommand();
            }

            return new { Success = true, message = "删除成功" };
        }

        /// <summary>
        /// 有数据删除标志设置的恢复
        /// </summary>
        /// <returns></returns>
        public dynamic PostRestore(ApiPostExtendModel data)
        {
            int userId = Convert.ToInt32(App.User?.FindFirstValue("UserID"));
            foreach (int id in data.ids)
            {
                db.Updateable<MenuRule>().SetColumns(n => new MenuRule() { DeleteFlag = 0, ModifyTime = DateTime.Now, ModifyUserID = userId }).Where(n => n.ID == id && n.DeleteFlag == 1).ExecuteCommand();
            }

            return new { Success = true, message = "恢复成功" };
        }

        #endregion
    }
}
